<?php
/**
 * Created by PhpStorm.
 * User: poptser@foxmail.com
 * Date: 2018/3/9
 * Time: 16:45
 */

namespace App\Http\Controllers\Sorting;

use App\Http\Controllers\ApiController;
use App\Services\Sorting\SortingNewService;
use App\Services\Sorting\SortingService;
use App\Services\SortingWeb\OrderService;
use App\Services\SortingWeb\ToolService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class SortingController extends ApiController{

    public $sortingService;
    public $orderService;
    public $toolService;    //辅助工具 service
    public $sortingNewService;    //辅助工具 service

    public $wid;
    public $userId;
    public $widInfo;
    public $kindeeSn;

    public function __construct(SortingService $sortingService,OrderService $orderService,
        ToolService $toolService,SortingNewService $sortingNewService){
        $this->sortingService = $sortingService;
        $this->orderService = $orderService;
        $this->toolService = $toolService;
        $this->sortingNewService = $sortingNewService;

        $isLogion = Auth::guard('sorting')->check();
        if(!$isLogion){
            $this->returnErr("api_token 不存在或已过期");
        }else{
            $this->userId = Auth::guard('sorting')->id();
            if($this->checkUserType(1,$this->userId)){
                $this->returnErr("您没有访问此接口得权限");
            }
        }

        $this->wid = $this->toolService->getUserWid($this->userId);

        $this->widInfo = $this->toolService->getWidInfo($this->wid);
        $this->kindeeSn = $this->widInfo->k3_number;
    }


    /**
     * 获取订单公司列表概览
     * Author:poptser@foxmail.com
     * @param Request $request
     * @return mixed
     */
    public function getCompanyOverview(Request $request){
        $showDate = $request->showDate;
        $showDate = date("Y-m-d",strtotime($showDate));
        $companyList = $this->sortingService->getCompanyList();
        //return $companyList;
        $returnData = [];
        foreach ($companyList as $key=>$value){
            $orderNum = $this->sortingService->getOrderNum($showDate,$value->id,
                null,null,$this->wid);
            if($orderNum['otherToday']==0&&$orderNum['today']==0){
                unset($companyList[$key]);
            }else{
                $value->orderNum  = $orderNum;
                $returnData[] = $value;
            }
        }

        if(empty($returnData)){
            return $this->success([]);
        }else{
            return $this->success($returnData,"已返回配送公司概览数据");
        }
    }

    /**
     * 获取时间列表概览
     * Author:poptser@foxmail.com
     * @param Request $request
     * @return mixed
     */
    public function getTimeList(Request $request){
        $showDate = $request->showDate;
        $showDate = date("Y-m-d",strtotime($showDate));
        $companyId = $request->companyId;
        $timeList = $this->sortingService->getDistributionTime($showDate,$companyId,null,$this->wid);
        //return $timeList;

        $timeList[] = (object)[
            'best_time'=>"超时订单",
        ];

        foreach ($timeList as $key=>$value){
            $value->orderNum = $this->sortingService->getOrderNum($showDate,
                $companyId,$value->best_time,null,$this->wid);
        }
        if(empty($timeList)){
            return $this->success([]);
        }else{
            return $this->success($timeList,"已返回时间分段概览数据");
        }
    }

    /**
     * 获取配送划区概览
     * Author:poptser@foxmail.com
     * @param Request $request
     * @return mixed
     */
    public function getZoneList(Request $request){
        $showDate = $request->showDate;
        $companyId = $request->companyId;
        $bestTime = $request->bestTime;
        $showDate = date("Y-m-d",strtotime($showDate));
        $zoneList = $this->sortingService->getDistributionZone($showDate,
            $companyId,$bestTime,$this->wid);
        //return $zoneList;
        foreach ($zoneList as $key=>$value){
            $value->orderNum = $this->sortingService->getOrderNum($showDate,
                $companyId,$bestTime,$value->area_id,$this->wid);
        }
        if(empty($zoneList)){
            return $this->success([]);
        }else{
            return $this->success($zoneList,"已返回区域概览数据");
        }
    }


    /**
     * 获取一个拣货单
     * Author:poptser@foxmail.com
     * @param Request $request
     * @return mixed
     * @throws \Exception
     */
    public function getSortingOrder(Request $request){
        $showDate = $request->showDate;         //日期
        $companyId = $request->companyId;       //配送公司
        $bestTime = $request->bestTime;         //配送时间
        $zoneId = $request->zoneId;             //划区ID
        //return $request;
        $showDate = date("Y-m-d",strtotime($showDate));
        if(empty($showDate)||!is_numeric($companyId)||empty($bestTime)||empty($zoneId)){

            return $this->failedReturn("参数错误");
        }
        $sortingOrder =$this->sortingService
            ->getSortingOrder($showDate,$companyId,$bestTime,$zoneId,$this->wid);
        //dump($sortingOrder);
        $sortingOrder = $sortingOrder[0];
        if(empty($sortingOrder)){
            return $this->failedReturn("暂无空闲拣货单");
        }
        $judgment = $this->sortingService->setSortingOrderStatus($sortingOrder->id,$this->userId,3);
        if($judgment===true){
            $ToolService = new ToolService();
            $sortingOrderIdList = $this->orderService->getOrderBySorting($sortingOrder->id);

            $data['sortingSn'] = $sortingOrder->sorting_sn;
            $data['sortingId'] = $sortingOrder->id;
            $data['orderNum'] = count($sortingOrderIdList);
            $data['goodsNum'] = $this->orderService->getGoodsNumByOrder($sortingOrderIdList);
            $data['zone'] = $ToolService->getAreaName($sortingOrder->area_id);
            return $this->success($data,"获取成功");
        }else{
            return $this->failedReturn("获取失败，稍后尝试");
        }
    }

    /**
     * 获取拣货单详情
     * Author:poptser@foxmail.com
     * @param Request $request
     * @return mixed
     */
    public function getSortingOrderInfo(Request $request){
        if(empty($request->sortingId)){
            return $this->failedReturn('缺少必要参数:sortingId');
        }
        $sortingOrderInfo =  $this->sortingService->getSortingOrderInfo($request->sortingId,$this->kindeeSn,
            $this->wid);
        if(!is_array($sortingOrderInfo)){
            return $this->failedReturn($sortingOrderInfo);
        }else{
            return $this->success($sortingOrderInfo,"拣货单详情已返回");
        }
    }



    /**
     * 获取已拣货历史列表
     * Author:poptser@foxmail.com
     * @param Request $request
     * @return mixed
     */
    public function getSortingHistory(Request $request){
        $showDate = $request->showDate;
        $showDate = date("Y-m-d",strtotime($showDate));
        $SortingHistory = $this->sortingService->getSortingHistory($showDate,$this->userId,$this->wid);
        if(!empty($SortingHistory)){
            return $this->successList($SortingHistory,"已获取到列表",1);
        }else{
            return $this->failedReturn("无数据");
        }
    }


    /**
     * 设置拣货单完成
     * Author:poptser@foxmail.com
     * @param Request $request
     * @return bool|mixed|string
     * @throws \Exception
     */
    public function setSortingOrderComplete(Request $request){
        $goodDate = json_decode($request->goodDate,true);

        //return $goodDate;
        if(!empty($goodDate)){
            //return $goodDate;
            $goodsChange = $this->checkGoodsChange($goodDate['goodsList'],$goodDate['sortingId']);
            if($goodsChange!==true){
                return $this->failedReturn($goodsChange);
            }
            //商品无变化
            //提取需退款商品
            $goodsRefund = $this->makeOrderGoodsRefund($goodDate['goodsList']);
            if(!empty($goodsRefund)){
                //退货
                $refundInfo = $this->sortingService->setSortingOrderOdd($goodsRefund,$this->userId);
                if($refundInfo!==true){
                    return $this->failedReturn($refundInfo);
                }
            }

            $judgment = $this->sortingService->setSortingOrderStatus($goodDate['sortingId'],$this->userId,4);
            if($judgment===true){
                return $this->success(null,"已完成");
            }else{
                return $this->failedReturn($judgment);
            }
        }else{
            return $this->failedReturn("json 数据异常");
        }
    }

    /**
     * 转换退款数据，由商品列表方式转到订单模式
     * Author:poptser@foxmail.com
     * @param $goods
     * @return mixed
     */
    private function makeOrderGoodsRefund($goods){
        $orderGoods = [];
        foreach ($goods as $good){
            foreach ($good['orderList'] as $order){
                if($order['lackNum']+$order['poorNum']>0){
                    $orderGoods[$order['orderId']][]=
                        [
                            "goodsSn"=>$good['goodsSn'],
                            "lackNum"=>$order['lackNum'],
                            "poorNum"=>$order['poorNum']
                        ];
                }
            }
        }
        $returnOrderGoods = [];
        foreach ($orderGoods as $key=>$orderGood){
            $returnOrderGoods[] = [
                "orderId"=>$key,
                "goodsList"=>$orderGood
            ];
        }
        return $returnOrderGoods;
    }

    /**
     * 检查商品有无变化
     * Author:poptser@foxmail.com
     * @param $userGoods
     * @param $sortingId
     * @return bool|string
     */
    private function checkGoodsChange($userGoods, $sortingId){
        $sortingInfo = $this->sortingService->getSortingOrderInfo($sortingId);
        $serverGoods = $sortingInfo['goodsList'];
        if(count($userGoods)==count($serverGoods)){
            foreach ($userGoods as $userGood){
                foreach ($serverGoods as $serverGood){
                    if($serverGood['goodsSn']==$userGood['goodsSn']){
                        if($serverGood['goodsNum']!=$userGood['goodsNum']){
                            return $serverGood['goodsName']." 商品数量已变动";
                        }
                    }
                }
            }
        }else{
            return "商品数量有变动，请仔细核对商品种类和数量！";
        }

        return true;

    }


    /**
     * 拣货中列表
     * Author:poptser@foxmail.com
     * @return mixed
     */
    public function getSortingIng(){
        $SortingHistory = $this->sortingService->getSortingIng($this->userId,$this->wid);
        if(!empty($SortingHistory)){
            return $this->successList($SortingHistory,"已获取到列表",1);
        }else{
            return $this->failedReturn("无数据");
        }
    }


    /**
     * 退拣货单
     * Author:poptser@foxmail.com
     * @param Request $request
     * @return mixed
     * @throws \Exception
     */
    public function setUnSortingIng(Request $request){
        $judgment = $this->sortingService->setSortingOrderStatus($request->SortingId,$this->userId,1);
        if($judgment===true){
            return $this->success(null,"退单成功");
        }else{
            return $this->failedReturn($judgment);
        }
    }

    /**
     * 获取订单概览情况
     * Author:poptser@foxmail.com
     * @return mixed
     */
    public function getOrderOverview(){
        //return "dd";
        $unSortingNum = $this->sortingNewService->getOrderNum(null,null,null,null,$this->wid);
        $sortingNum = $this->sortingService->getSortingIng($this->userId,$this->wid,true);
        $UnQualityNum = $this->sortingService->getUnQualityNum($this->wid);
        $data['unSortingNum'] = $unSortingNum['today'];
        $data['sortingNum'] = $sortingNum;
        $data['UnQualityNum'] = $UnQualityNum;
        return $this->success($data,"数据已返回");
    }

    /**
     * 打印拣货单
     * Author:poptser@foxmail.com
     * @param $request
     * @return mixed
     */
    public function sortingOrderPrint(Request $request){
        $sortingInfo = $this->sortingService->getSortingOrderPrint($request->sortingId);
        $printInfo = [];
        foreach ($sortingInfo as $item){
            $printOne = $item['orderArea']."\n";
            $printOne .= $item['bestTime']."\n";
            $printOne .= "============商品信息============\n";

            foreach ($item['goodsInfo'] as $good){
                $printOne .= $good['goodsName']."\n";
                $printOne .= $good['goodsSn']."\n";
                $printOne .= "价:".$good['goodsPrice']."*".$good['goodsNum']." 折:".$good['discountPrice']." 计:".$good['goodsPrice']*$good['goodsNum']."\n";
                $printOne .= "配货合计:".$good['goodsNum']."\n";
            }
            $printOne .= "关联拣货单：".$item['sortingSn']."\n";
            $printOne .= $item['sortingName']." ".$item['sortingTime']."\n";
            $printInfo[] = [
                'text'=>$printOne,
                'orderId'=>$item['orderId'],
                'orderSn'=>$item['orderSn'],
                'sortingNum'=>$item['sortingNum']." 号篮子",
                'orderArea'=>$item['orderArea'],
                'bestTime'=>$item['bestTime'],
            ];
        }
        return $this->success($printInfo);
    }

    /**
     * 获取配货统计
     * Author:poptser@foxmail.com
     */
    public function getSortingCount(){
        //本日
        $startTime=mktime(0,0,0,date('m'),date('d'),date('Y'));
        $endTime=mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
        $data['todayNum'] = $this->sortingService->gerCompleteOrderNumByDate($startTime,$endTime,$this->userId);


        //本周完成订单数
        $startTime=mktime(0,0,0,date('m'),date('d')-date('w')+1,date('Y'));
        $endTime=mktime(23,59,59,date('m'),date('d')-date('w')+7,date('Y'));
        $data['weekNum']=$this->sortingService->gerCompleteOrderNumByDate($startTime,$endTime,$this->userId);

        //本月完成订单数
        $startTime=mktime(0,0,0,date('m'),1,date('Y'));
        $endTime=mktime(23,59,59,date('m'),date('t'),date('Y'));
        $data['monthNum']=$this->sortingService->gerCompleteOrderNumByDate($startTime,$endTime,$this->userId);

        $data['allNum']=$this->sortingService->gerCompleteOrderNumByDate(null,null,$this->userId);
        return $this->success($data);
    }
}
